#!/usr/bin/python
import cgi
import cgitb
import os
import sys
from pygallib import usersession
from pygallib import layoutlib
from pygallib import albumlib
from pygallib import userlib
from pygallib import picturelib

# Enable debug print
cgitb.enable()

logged_in = usersession.logged_in()
user = None
if logged_in:
  user = usersession.get_session_user()

headers = {}
headers["Content-type"] = "text/html"
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Home")
print("<body>")
menu = []
menu.append(("Home", "gallery.cgi"))
layoutlib.print_page_header(menu, user)
print('<div id="page_body">')

# Get the fields from url
fields = cgi.FieldStorage()
form_errors = []
form_result = ""
if "password" in fields:
  new_user = {}
  username = fields["username"].value
  password = fields["password"].value
  password_confirm = fields["password_confirm"].value
  # Validate username
  if len(username) > 0:
    new_user["username"] = username
  else:
    form_errors.append("Please input a longer username")
  # Validate password
  if len(password) > 0 and password == password_confirm:
    new_user["password"] = userlib.hash_password(password)
  else:
    form_errors.append("Passwords do not match")
  # Create user
  if len(form_errors) == 0:
    userlib.create_user(new_user)
    form_result = "Successfully created new user: %s" % username

print('<h1>Register</h1>')
for error in form_errors:
  print('<p>%s</p>' % error)
if len(form_result) > 0:
  print('<p>%s</p>' % form_result)
print("""
<form method="post" action="register.cgi">
  <ul>
    <li>
      <label for="username">Username:</label>
      <input type="text" name="username" value="" />
    </li>
    <li>
      <label for="password">Password:</label>
      <input type="password" name="password" value="" />
    </li>
    <li>
      <label for="password_confirm">Confirm password:</label>
      <input type="password" name="password_confirm" value="" />
    </li>
    <li>
      <input type="submit" value="Submit" />
    </li>
  </ul>
</form>
""")

print('</div>')
layoutlib.print_page_close()
